package com.zygvip.demand.core;

import com.zygvip.demand.constant.WechatSession;
import com.zygvip.demand.token.AppToken;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public abstract class BaseController {

    protected <E> Result  makeResult(int code,E data,String message){
        Result result = new Result();
        result.setCode(code);
        result.setData(data);
        result.setMsg(message);
        return result;
    }

    protected <E> Result  makeResult(int code,E data){
        Result result = new Result();
        result.setCode(code);
        result.setData(data);
        result.setMsg(null);
        return result;
    }

    protected ModelAndView getModel(){
        ModelAndView modelAndView = new ModelAndView();
        return modelAndView;
    }

    protected HttpServletRequest getRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }

    protected AppToken getSession(){
        HttpServletRequest request = getRequest();
        HttpSession session = request.getSession(false);
        Object value = session.getAttribute(WechatSession.SESSION_KEY);
        if(null != value && value instanceof AppToken){
            return (AppToken)value;
        }
        return null;
    }

    protected AppToken getSession(HttpSession session){
        Object value = session.getAttribute(WechatSession.SESSION_KEY);
        if(null != value && value instanceof AppToken){
            return (AppToken)value;
        }
        return null;
    }

    protected Integer getUserId(HttpSession session){
        Object value = session.getAttribute(WechatSession.SESSION_KEY);
        if(null != value && value instanceof AppToken){
            AppToken token = (AppToken)value;
            return token.getUserId();
        }
        return null;
    }

    protected String getOpenId(HttpSession session){
        Object value = session.getAttribute(WechatSession.SESSION_KEY);
        if(null != value && value instanceof AppToken){
            AppToken token = (AppToken)value;
            return token.getOpenId();
        }
        return null;
    }

}